package com.webank.wedatasphere.qualitis.controller.thymeleaf;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.webank.wedatasphere.qualitis.project.dao.repository.DatasourceManagerRepository;
import com.webank.wedatasphere.qualitis.project.dao.repository.ProjectFileRepository;
import com.webank.wedatasphere.qualitis.project.dao.repository.ProjectMenuRepository;
import com.webank.wedatasphere.qualitis.project.entity.*;
import com.webank.wedatasphere.qualitis.response.Grid;
import com.webank.wedatasphere.qualitis.response.Resp;
import com.webank.wedatasphere.qualitis.util.CreateTreeUtils;
import com.webank.wedatasphere.qualitis.util.LocalTimeUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.*;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/datasource")
public class DatasourceManagerController {

    /**
     * 数据源
     */
    @Autowired
    private DatasourceManagerRepository datasourceManagerRepository;


    @RequestMapping(value = {"/datagrid"}, method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public Grid<?> getCountIndex(HttpServletRequest request) {
        Sort sort = new Sort(Sort.Direction.ASC, "id");
        //  分页查询
        String page = request.getParameter("page");
        String limit = request.getParameter("rows");
        // 获取条件过滤器
        JSONObject changeBuilder = getJsonObject(request);
        // 组装SQl条件过滤法器
        ExampleMatcher matcher = getSqlWhere(request);
        // 序列化对象
        DataSourcePoJo itemQueryWhere = changeBuilder.toJavaObject(DataSourcePoJo.class);
        // 分页插件
        Pageable pageable = PageRequest.of(Integer.parseInt(page) - 1, Integer.parseInt(limit), sort);
        // 条件过滤器插件
        Example<DataSourcePoJo> example = Example.of(itemQueryWhere, matcher);
        // 条件过滤+分页
        Page<DataSourcePoJo> all = datasourceManagerRepository.findAll(example, pageable);
        List<DataSourcePoJo> content = all.getContent();
        long totalElements = all.getTotalElements();
        return Grid.OkPage(CollectionUtils.isEmpty(content)?new ArrayList<>():content, totalElements);
    }


    /**
     * 问题工单
     *
     * @return
     */
    @RequestMapping(value = {"/list"}, method = RequestMethod.GET)
    public ModelAndView datasource(HttpServletRequest request) {
        return new ModelAndView("layui-admin/datasource/list");
    }

    /**
     * 问题工单
     *
     * @return
     */
    @RequestMapping(value = {"/detail"}, method = RequestMethod.GET)
    public ModelAndView detail(HttpServletRequest request) {
        ModelAndView view = new ModelAndView("layui-admin/datasource/detail");
        String id = request.getParameter("id");
        if (StringUtils.isNotBlank(id)) {
            datasourceManagerRepository.findById(Long.valueOf(id)).ifPresent(view::addObject);
        } else {
            view.addObject(new DataSourcePoJo());
        }
        return view;
    }


    public static JSONObject getJsonObject(HttpServletRequest request) {
        JSONObject changeBuilder = new JSONObject();
        String filterRules = request.getParameter("filterRules");
        if (StringUtils.isNotEmpty(filterRules)) {
            JSONArray filters = JSONArray.parseArray(filterRules);
            for (int i = 0; i < filters.size(); i++) {
                JSONObject item = filters.getJSONObject(i);
                changeBuilder.put(item.getString("field"), item.getString("value"));
            }
        }
        return changeBuilder;
    }

    public static ExampleMatcher getSqlWhere(HttpServletRequest request) {
        ExampleMatcher withMatcher = ExampleMatcher.matching();
        String filterRules = request.getParameter("filterRules");
        if (StringUtils.isNotEmpty(filterRules)) {
            JSONArray filters = JSONArray.parseArray(filterRules);
            for (int i = 0; i < filters.size(); i++) {
                JSONObject item = filters.getJSONObject(i);
                // 模糊匹配
                withMatcher = withMatcher.withMatcher(item.getString("field"), ExampleMatcher.GenericPropertyMatchers.contains());
            }
        }
        return withMatcher;
    }


    @RequestMapping(value = {"/updateOrSave"}, method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public Resp<DataSourcePoJo> updateOrSave(DataSourcePoJo dataSourcePoJo) {
        if (dataSourcePoJo.getId() == null) {
            dataSourcePoJo.setCreateTime(LocalTimeUtils.getCurrentTime());
            dataSourcePoJo.setUpdateTime(LocalTimeUtils.getCurrentTime());
            dataSourcePoJo.setCreator("admin");
        } else {
            dataSourcePoJo.setUpdateTime(LocalTimeUtils.getCurrentTime());
        }
        datasourceManagerRepository.saveAndFlush(dataSourcePoJo);
        return Resp.Ok();
    }

    @RequestMapping(value = {"/remove"}, method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    @Transactional
    public Resp<DataSourcePoJo> remove(HttpServletRequest request) {
        String ids = request.getParameter("ids");
        if (StringUtils.isNotBlank(ids)) {
            String[] split = ids.split(",");
            for (String id : split) {
                datasourceManagerRepository.deleteById(Long.valueOf(id));
            }
        }
        return Resp.Ok();
    }
}
